package org.cuckoocs.xyfile.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import org.cuckoocs.xyfile.tool.Tool;

public class XYFileData<T extends Serializable> extends ByteFile {
	
	private int key;
	private int pass;
	private T data;
	
	public XYFileData(byte[] bytes) {
		repair(bytes);
	}

	public XYFileData(int key, int pass, T data) {
		super();
		this.key = key;
		this.pass = pass;
		this.data = data;
	}
	

	public int getKey() {
		return key;
	}

	public void setKey(int key) {
		this.key = key;
	}

	public int getPass() {
		return pass;
	}

	public void setPass(int pass) {
		this.pass = pass;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	@Override
	public byte[] toByte() {
		byte[] buff = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		try (DataOutputStream dos = new DataOutputStream(baos)){
			dos.writeInt(key);
			dos.writeInt(pass);
			dos.write(data.serialization());
			
			buff = baos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buff;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void repair(byte[] bytes) {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		try (DataInputStream dis = new DataInputStream(bais)){
			this.key = dis.readInt();
			this.pass = dis.readInt();
			
			ObjectInputStream ois = new ObjectInputStream(dis);
			this.data = (T)ois.readObject();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	
	
	public long unique(){
		return Tool.unique(key, pass);
	}
	
	@Override
	public String toString() {
		return "XYFileData [key=" + key + ", pass=" + pass + ", data=" + data
				+ "]";
	}
	
	
}
